Components.utils.import("resource://lucidity/lucidapi.jsm");

(function() {

    this.lucidctx = new (lucidapi.CryptoOperator.extend(function(classref) { return {
        initialize: function()
        {
            classref.superClass.initialize.call(this,window);
        },
        getInvocationTarget: function()
        {
            return document.getElementById("result-textbox").value;
        }
    }}));

    var threadMgr = Components.classes["@mozilla.org/thread-manager;1"].getService();

    var keygenRunnable = lucidapi.AbstractClass.extend(function(classref) { return {
        initialize: function(threadID, userid, passphrase, keysize, subsize, expiresecs)
        {
            classref.superClass.initialize.call(this);
            this.threadID = threadID;
            this.userid = userid;
            this.passphrase = passphrase;
            this.subsize = subsize;
            this.keysize = keysize;
            this.expiresecs = expiresecs;
        },

        run: function() {
            var result = null;
            try {
                if (threadMgr.isMainThread)
                {
                    // This is where we react to the completion of the working thread.
                    var resultbox = document.getElementById("result-textbox");
                    resultbox.value = this.userid;
                }
                else
                {
                    // This is where the working thread does its processing work.
                    result = lucidapi.generateKeys(this.userid,this.passphrase,this.keysize,this.subsize,this.expiresecs);
                    // When it's done, call back to the main thread to let it know
                    // we're finished.
                    threadMgr.mainThread.dispatch(new keygenRunnable(this.threadID, result), threadMgr.mainThread.DISPATCH_NORMAL);
                }
            } catch(e) {
                lucidapi.error(e);
            }
        },

        QueryInterface: function(iid) {
            if (iid.equals(Components.interfaces.nsIRunnable) ||
                iid.equals(Components.interfaces.nsISupports)) {
                return this;
            }
            throw Components.results.NS_ERROR_NO_INTERFACE;
        }
    }});

    function hasGoodData()
    {
        return lucidapi.hasArmorType(document.getElementById("result-textbox").value,"PRIVATE KEY BLOCK");
    }

    this.onKeygenPageShow = function()
    {
        document.getElementById("keygenDeck").selectedIndex = 0;
    }

    this.onExpirationChecked = function()
    {
        var expCheckbox = document.getElementById("neverexpireCheckbox");
        var expPicker = document.getElementById("expirationDatepicker");
        expPicker.disabled = expCheckbox.checked;

    }

    this.onKeygenPageAdvanced = function()
    {
        var realname = document.getElementById("realname-textbox").value;
        var email = document.getElementById("email-textbox").value;
        if (realname.length < 5)
        {
            lucidapi.promptAlert("luciderr.minNameLen",[]);
            return false;
        }
        if (email.length > 0 && email.indexOf("@") < 1)
        {
            lucidapi.promptAlert("luciderr.invalidEmail",[]);
            return false;
        }
        var password = document.getElementById("passphrase-textbox").value;
        var confirm = document.getElementById("passconfrm-textbox").value;
        if (password != confirm)
        {
            lucidapi.promptAlert("luciderr.pwConfirmMismatch",[]);
            return false;
        }
        document.getElementById("result-textbox").value = "";
        var keysize = parseInt(document.getElementById("keysizeRadiogroup").value,10);
        var subsize = parseInt(document.getElementById("subsizeRadiogroup").value,10);
        var comment = document.getElementById("comment-textbox").value;
        var userid = realname;
        var expiresecs = 0;
        if (!document.getElementById("neverexpireCheckbox").checked)
        {
            var curDate = new Date();
            var expDate = document.getElementById("expirationDatepicker").dateValue;
            var delta = expDate.getTime() - curDate.getTime();
            if (delta < 0)
            {
                delta = 0;
            }
            else
            {
                delta = Math.round(delta / 1000);
            }
            expiresecs = delta;
        }

        userid += comment.length > 0 ? (" (" + comment + ")") : "";
        userid += email.length > 0 ? (" <" + email + ">") : "";
        var keygenDeck = document.getElementById("keygenDeck");
        try {
            keygenDeck.selectedIndex = 1;
            var background = threadMgr.newThread(0);
            background.adjustPriority(20);
            background.dispatch(new keygenRunnable(1, userid,password,keysize,subsize,expiresecs), threadMgr.mainThread.DISPATCH_NORMAL);
            background.shutdown();
        } catch(e) {
            lucidapi.error(e);
        }
        if (!hasGoodData())
        {
            keygenDeck.selectedIndex = 0;
            alert("There was a problem generating your keys!");
            return false;
        }
        return true;
    }

    this.onFinishPageShow = function()
    {
        document.getElementById("finishDeck").selectedIndex = hasGoodData() ? 1 : 0;
    }

    this.onFinish = function(win)
    {
        if (hasGoodData())
        {
            var doimport = document.getElementById("import-checkbox").checked;
            if (doimport)
                return lucidctx.invokeOperation({opname:'import'});
        }
        return true;
    }

    this.onLoad = function(win)
    {
        document.getElementById("result-textbox").value = lucidapi.i18n.getString("luciderr.keygenFailure");
/*
        if (lucidapi.config.confirm_keyring_changes)
        {
            var doimportchkbox = document.getElementById("import-checkbox");
            doimportchkbox.checked = false;
            doimportchkbox.disabled = true;
            doimportchkbox.setAttribute("tooltiptext",lucidapi.i18n.getString("disabledCuzROKeyring"));
        }
*/

        var showintro = false;
        if (win.arguments.length > 0){
            showintro = win.arguments[0];
        }

        if (!showintro)
        {
            document.getElementById("lucid-keygen-wizard").goTo("keygenPage");
        }
        else if (!lucidapi.masterKeyset.isEmpty())
        {
            document.getElementById("welcomePage").next = "finishPage";
        }
        else
        {
            try {
                var lucidkeydata = lucidapi.getContent("chrome://lucidity/content/pub-key-lucidity.asc");
                lucidapi.masterKeyset.skipConfirm = true;
                lucidapi.masterKeyset.importKeyData(lucidkeydata);
            } catch (e) {
            } finally {
                delete lucidapi.masterKeyset.skipConfirm;
            }
        }
        sizeToContent();
    }

})();
